/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.rest;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.system.domain.Courseteacher;
import me.zhengjie.modules.system.domain.Departmentteacher;
import me.zhengjie.modules.system.domain.Teacher;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.service.CourseteacherService;
import me.zhengjie.modules.system.service.DepartmentteacherService;
import me.zhengjie.modules.system.domain.vo.DepartmentteacherQueryCriteria;
import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import me.zhengjie.modules.system.service.TeacherService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.utils.R;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import me.zhengjie.utils.PageResult;

/**
* @author shitou
* @date 2024-12-12
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "部门教师管理")
@RequestMapping("/api/departmentteacher")
public class DepartmentteacherController {

    private final DepartmentteacherService departmentteacherService;

    private final TeacherService teacherService;

    private final UserService userService;

    private final CourseteacherService courseTeacherService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
//    @PreAuthorize("@el.check('departmentteacher:list')")
    public void exportDepartmentteacher(HttpServletResponse response, DepartmentteacherQueryCriteria criteria) throws IOException {
        departmentteacherService.download(departmentteacherService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询部门教师")
    @ApiOperation("查询部门教师")
//    @PreAuthorize("@el.check('departmentteacher:list')")
    public ResponseEntity<PageResult<Departmentteacher>> queryDepartmentteacher(DepartmentteacherQueryCriteria criteria, Page<Object> page){
        return new ResponseEntity<>(departmentteacherService.queryAll(criteria,page),HttpStatus.OK);
    }

    @GetMapping("/getDepartmentteacherList")
    @Log("查询部门教师")
    @ApiOperation("查询部门教师")
//    @PreAuthorize("@el.check('departmentteacher:list')")
    public ResponseEntity<List<Map<String,Object>>> getDepartmentteacherList(DepartmentteacherQueryCriteria criteria, Page<Object> page){

        List<Departmentteacher> departmentteacherList = departmentteacherService.getDepartmentteacherList(criteria);
        List<Integer> integers = new ArrayList<>();
        for(Departmentteacher departmentteacher : departmentteacherList){
            integers.add(departmentteacher.getTeacherId());
        }
        List<Teacher> teacherList = new ArrayList<>();
        if(integers.size()!=0){
            teacherList = teacherService.listByIds(integers);
        }
        List<Map<String,Object>> list = new ArrayList<>();

        QueryWrapper queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("dempartmentId",criteria.getDepartmentId());
        queryWrapper.eq("courseId",criteria.getCourseId());
        List<Courseteacher> courseteacherList = courseTeacherService.list(queryWrapper);


        List<Integer> userIds = new ArrayList<>();
        for(Teacher teacher:teacherList){
            Map<String,Object> map = new HashMap<>();

            map.put("userId",teacher.getUserid());
            userIds.add(Math.toIntExact(teacher.getUserid()));
            map.put("id",teacher.getId());
            for(Departmentteacher departmentteacher :departmentteacherList){
                if(departmentteacher.getTeacherId() == Math.toIntExact(teacher.getId())){
                    map.put("type",departmentteacher.getType());
                    map.put("departmentteacherId",departmentteacher.getId());
                }
            }

            map.put("number",teacher.getNumber());
            map.put("email",teacher.getEmail());
            map.put("phone",teacher.getPhone());
            map.put("gender",teacher.getGender());
            map.put("avatarName",teacher.getAvatarName());
            map.put("avatarPath",teacher.getAvatarPath());
            map.put("username",teacher.getUsername());
            map.put("nickName",teacher.getNickName());
            map.put("password",teacher.getPassword());
            map.put("enabled",teacher.getEnabled());

            List<Integer> chapterIds = new ArrayList<>();
            for(Courseteacher courseteacher:courseteacherList){
                if(courseteacher.getTeacherId() == Math.toIntExact(teacher.getId())){
                    chapterIds.add(courseteacher.getCourseChapterId());
                }
            }
            map.put("chapterIds",chapterIds);
            list.add(map);

        }

        //获取用户列表
//        QueryWrapper queryWrapper = new QueryWrapper<>();
//        queryWrapper.in("id",userIds);
//        List<User> userList = userService.list(queryWrapper);
//
//        for(User user:userList){
//            for(Map<String,Object> map:list){
//                if(map.get("userId") == user.getId()){
//                    map.put("password",user.getPassword());
//                }
//            }
//        }
        return new ResponseEntity<>(list,HttpStatus.OK);
    }

    @GetMapping("/getCourseDepartmentteacherList")
    @Log("查询部门教师")
    @ApiOperation("查询部门教师")
//    @PreAuthorize("@el.check('departmentteacher:list')")
    public ResponseEntity<List<Map<String,Object>>> getCourseDepartmentteacherList(DepartmentteacherQueryCriteria criteria, Page<Object> page){

        List<Departmentteacher> departmentteacherList = departmentteacherService.getCourseDepartmentteacherList(criteria);
        List<Integer> integers = new ArrayList<>();
        for(Departmentteacher departmentteacher : departmentteacherList){
            integers.add(departmentteacher.getTeacherId());
        }
        List<Teacher> teacherList = new ArrayList<>();
        if(integers.size()!=0){
            teacherList = teacherService.listByIds(integers);
        }
        List<Map<String,Object>> list = new ArrayList<>();

        QueryWrapper queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("dempartmentId",criteria.getDepartmentId());
        queryWrapper.eq("courseId",criteria.getCourseId());
        List<Courseteacher> courseteacherList = courseTeacherService.list(queryWrapper);


        List<Integer> userIds = new ArrayList<>();
        for(Teacher teacher:teacherList){
            Map<String,Object> map = new HashMap<>();

            map.put("userId",teacher.getUserid());
            userIds.add(Math.toIntExact(teacher.getUserid()));
            map.put("id",teacher.getId());
            for(Departmentteacher departmentteacher :departmentteacherList){
                if(departmentteacher.getTeacherId() == Math.toIntExact(teacher.getId())){
                    map.put("type",departmentteacher.getType());
                    map.put("departmentteacherId",departmentteacher.getId());
                }
            }

            map.put("number",teacher.getNumber());
            map.put("email",teacher.getEmail());
            map.put("phone",teacher.getPhone());
            map.put("gender",teacher.getGender());
            map.put("avatarName",teacher.getAvatarName());
            map.put("avatarPath",teacher.getAvatarPath());
            map.put("username",teacher.getUsername());
            map.put("nickName",teacher.getNickName());
            map.put("password",teacher.getPassword());
            map.put("enabled",teacher.getEnabled());

            List<Integer> chapterIds = new ArrayList<>();
            for(Courseteacher courseteacher:courseteacherList){
                if(courseteacher.getTeacherId() == Math.toIntExact(teacher.getId())){
                    chapterIds.add(courseteacher.getCourseChapterId());
                }
            }
            map.put("chapterIds",chapterIds);
            list.add(map);

        }

        //获取用户列表
//        QueryWrapper queryWrapper = new QueryWrapper<>();
//        queryWrapper.in("id",userIds);
//        List<User> userList = userService.list(queryWrapper);
//
//        for(User user:userList){
//            for(Map<String,Object> map:list){
//                if(map.get("userId") == user.getId()){
//                    map.put("password",user.getPassword());
//                }
//            }
//        }
        return new ResponseEntity<>(list,HttpStatus.OK);
    }


    @PostMapping
    @Log("新增绑定部门教师")
    @ApiOperation("新增绑定部门教师")
    public ResponseEntity<Object> createDepartmentteacher(@Validated @RequestBody Departmentteacher resources){
        departmentteacherService.create(resources);
        return new ResponseEntity<>("添加成功",HttpStatus.CREATED);
    }
    @PostMapping("/saveDepartmentteacher")
    @Log("新增部门教师")
    @ApiOperation("新增部门教师")

    public R<Object> saveDepartmentteacher(@Validated @RequestBody Teacher resources){

        Integer status = teacherService.create(resources);

        if(status == -1){
            return R.error("邮箱重复");
        }
        if(status == -3){
            return R.error("用户名已存在");
        }
        if(status == -4){
            return R.error("手机号重复");
        }
        if(status == -5){
            return R.error("工号重复");
        }



        Departmentteacher departmentteacher = new Departmentteacher();
        departmentteacher.setTeacherId(Math.toIntExact(resources.getId()));
        departmentteacher.setDepartmentId(resources.getDepartmentId());
        departmentteacherService.create(departmentteacher);
        return R.success("新增成功");
    }
    @PutMapping
    @Log("修改部门教师")
    @ApiOperation("修改部门教师")
//    @PreAuthorize("@el.check('departmentteacher:edit')")
    public ResponseEntity<Object> updateDepartmentteacher(@Validated @RequestBody Departmentteacher resources){

        //取消其他部门教师表
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("departmentId",resources.getDepartmentId());
        List<Departmentteacher> DepartmentList = departmentteacherService.list(queryWrapper);


        for(Departmentteacher departmentteacher:DepartmentList){
            if(departmentteacher.getType() == 1){
                departmentteacher.setType(0);
                departmentteacherService.update(departmentteacher);

            }


        }
        departmentteacherService.update(resources);

        Map<String,Object> map = new HashMap<>();
        map.put("message","设置成功");

        return new ResponseEntity<>(map, HttpStatus.valueOf(201));
    }

    @DeleteMapping
    @Log("删除部门教师")
    @ApiOperation("删除部门教师")
//    @PreAuthorize("@el.check('departmentteacher:del')")
    public ResponseEntity<Object> deleteDepartmentteacher(@RequestBody List<Integer> ids) {
        departmentteacherService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}